import {
    Button,
    Modal,
    Form,
    Input,
    DatePicker,
    Select,
    Space,
    Row,
    Col,
    message,
    Table,
} from 'antd';
import { useState } from 'react';
import { useAntdTable } from 'ahooks';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useFormModal } from '@/hooks/useFormModal';
import {
    deleteCustomerBack,
    opsCustomerOperateList,
    internalCustomerBack,
} from '@/config/request/opsManager';

import OpsCustomerTag from './opsCustomerTag/index';
import './index.scss';

const OpsCustomer: React.FC = () => {
    const [form] = Form.useForm();
    const formMemberModal = useFormModal();
    const [fromData, setFromData] = useState<any>();
    const [isDelete, setIsDelete] = useState(false);

    const { tableProps, search } = useAntdTable(
        async ({ pageSize, current: pageNum }) => {
            const { publishDate } = form.getFieldsValue();
            const params = {
                ...form.getFieldsValue(),
                startTime: publishDate?.[0]?.format('YYYY-MM-DD 00:00:00'),
                endTime: publishDate?.[1]?.format('YYYY-MM-DD 23:59:59'),
                pageNum,
                pageSize,
                // supplierType
            };
            delete params.publishDate;
            const res = await opsCustomerOperateList(params);
            return {
                total: res.data.data?.total ?? 0,
                list: res.data.data?.list ?? [],
            };
        },
        { defaultPageSize: 10, form }
    );

    const columns: ColumnsType<any> = [
        {
            title: '客户id',
            dataIndex: 'customerId',
            key: 'customerId',
            width: 5,
        },
        {
            title: '客户名称',
            dataIndex: 'customerName',
            key: 'customerName',
            width: 5,
        },
        {
            title: '客户超级id',
            key: 'superCustomerId',
            dataIndex: 'superCustomerId',
            width: 5,
        },
        {
            title: '用户手机号',
            dataIndex: 'mobilePhone',
            key: 'mobilePhone',
            width: 5,
        },
        {
            title: '是否内部用户',
            dataIndex: 'internalFlag',
            key: 'internalFlag',
            width: 5,
            render: (value) => {
                if (value === 1) {
                    return <span>{'是'}</span>;
                } else {
                    return <span>{'否'}</span>;
                }
            },
        },
        {
            title: '操作类型',
            dataIndex: 'operateType',
            key: 'operateType',
            width: 8,
        },
        {
            title: '工单编号',
            key: 'workOrderId',
            dataIndex: 'workOrderId',
            width: 5,
        },
        {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            width: 5,
            render: (text) => {
                if (text === '失败') {
                    return <span style={{ color: 'red' }}>{[text]}</span>;
                }
                if (text === '成功') {
                    return <span style={{ color: 'green' }}>{[text]}</span>;
                }
            },
        },
        {
            title: '操作人',
            key: 'operatePerson',
            dataIndex: 'operatePerson',
            width: 8,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 100,
            render: (text) =>
                text === null ? text : dayjs(text).format('YYYY-MM-DD'),
        },
    ];

    const handleChildCallback = (result) => {
        setFromData(result);
    };

    // 新增/修改需求信息
    const editMemebershipChange = async () => {
        try {
            console.log(fromData);
            if (!fromData.superCustomerId) {
                return message.error('请先查询后再提交！！');
            }

            const response = isDelete
                ? await internalCustomerBack(fromData)
                : await deleteCustomerBack(fromData);

            if (response.data.code === 200) {
                message.success('保存成功！');
                formMemberModal.modal.close();
                // 重新打开会员赠送的界面
                search.submit();
                setFromData({});
            }
        } catch (error: any) {
            return message.error('必填项未填！！');
        }
    };

    return (
        <div className="bg-white p-2.5">
            <Form form={form} name="supplierList_search">
                <Row>
                    <Col span={4}>
                        <Form.Item label="客户名称" name="customerName">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="创建时间" name="publishDate">
                            <DatePicker.RangePicker
                                placeholder={['开始日期', '结束日期']}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={24} style={{ textAlign: 'right' }}>
                        <Form.Item>
                            <Space size="small">
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    onClick={search.submit}
                                >
                                    搜索
                                </Button>
                                <Button type="primary" onClick={search.reset}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{ textAlign: 'left', marginBottom: 16 }}>
                    <Button
                        type="primary"
                        className="mt-5 mb-5"
                        onClick={() => {
                            formMemberModal.modal.open();
                            setIsDelete(true);
                        }}
                    >
                        标记内部用户
                    </Button>

                    <Button
                        type="primary"
                        className="mt-5 mb-5"
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                            formMemberModal.modal.open();
                            setIsDelete(false);
                        }}
                    >
                        删除用户
                    </Button>
                </div>

                <Table
                    {...tableProps}
                    bordered
                    columns={columns}
                    pagination={{
                        ...tableProps.pagination,
                        showQuickJumper: true,
                        showTotal: (total) => `总计 ${total} `,
                    }}
                    // showQuickJumper defaultCurrent={2} total={500} onChange={onChange}
                    rowKey="bugId"
                    locale={{ emptyText: '暂无数据' }}
                    scroll={{ x: 'calc(0vw + 10px)' }}
                />
            </Form>
            <Modal
                width={1200}
                destroyOnClose
                open={formMemberModal.isOpen}
                onOk={() => editMemebershipChange()}
                onCancel={() => {
                    formMemberModal.modal.close();
                    setFromData({});
                }}
                title={isDelete ? '标记内部用户' : '删除用户'}
                className="formMemberModal"
                okText="提交"
                cancelText="取消"
                maskClosable={false}
            >
                <OpsCustomerTag
                    formModal={formMemberModal}
                    onCallback={handleChildCallback}
                />
            </Modal>
        </div>
    );
};

export default OpsCustomer;
